﻿using Autoupdate.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace GDF.AutoupdateConfig
{
    public partial class MainForm : Form
    {
        public const string ConfigFile = "config.cfg";

        private const string ModuleName = "ModuleName";

        private DataTable mVersionTable;
        private DataTable mFileTable;
        private Configuration mConfig;
        private string mModuleName;
        public string AssemblyVersion
        {
            get
            {
                return Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
        }
        public MainForm()
        {
            InitializeComponent();

            mVersionTable = new DataTable();
            mFileTable = new DataTable();
            mConfig = new Configuration(null);
            mModuleName = string.Empty;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                mConfig.Load(Path.Combine(Application.StartupPath, ConfigFile));
                mModuleName = mConfig.ReadString(ModuleName);

                LoadModule();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void LoadModule()
        {
            btnCreateTestUpdateFiles.Enabled = false;
            btnbtnCreateUpdateFiles.Enabled = false;

            cboModule.Items.Clear();
            using (DataTable table = new DataTable())
            {
                DBHelper.FillTable("SELECT " + SysUpdateVersion.Module + " FROM " + SysUpdateVersion.TableName
                    + " GROUP BY " + SysUpdateVersion.Module
                    + " ORDER BY " + SysUpdateVersion.Module,
                    table);
                cboModule.BeginUpdate();
                cboModule.Items.Add(string.Empty);
                foreach (DataRow dr in table.Rows)
                    cboModule.Items.Add(dr[SysUpdateVersion.Module].ToString());
                cboModule.EndUpdate();
            }
            if (!string.IsNullOrEmpty(mModuleName))
                cboModule.SelectedIndex = cboModule.Items.IndexOf(mModuleName);

            if (!string.IsNullOrEmpty(cboModule.Text))
            {
                btnCreateTestUpdateFiles.Enabled = true;
                btnbtnCreateUpdateFiles.Enabled = true;
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            try
            {
                mConfig.Save(Path.Combine(Application.StartupPath, ConfigFile));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnCreateTestUpdateFiles_Click(object sender, EventArgs e)
        {
            try
            {
                CreateUpdateFiles(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnbtnCreateUpdateFiles_Click(object sender, EventArgs e)
        {
            try
            {
                CreateUpdateFiles(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void cboModule_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboModule.SelectedIndex != -1)
                    mModuleName = cboModule.Items[cboModule.SelectedIndex].ToString();
                LoadVersionData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void dgvVersion_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                LoadFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void dgvVersion_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.Button != MouseButtons.Left)
                    return;
                DataGridViewSelectedRowCollection selectedRows = dgvVersion.SelectedRows;
                if (selectedRows.Count == 0)
                    return;
                if (e.RowIndex != selectedRows[0].Index)
                    return;
                LoadFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnAddVersion_Click(object sender, EventArgs e)
        {
            try
            {
                VersionEditForm form = new VersionEditForm(cboModule.Items, cboModule.SelectedIndex, mVersionTable, -1);
                form.Text = "新增版本";
                if (form.ShowDialog() == DialogResult.OK)
                {
                    LoadModule();
                    LoadVersionData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnModifyVersion_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewSelectedRowCollection selectedRows = dgvVersion.SelectedRows;
                if (selectedRows.Count == 0)
                    return;
                VersionEditForm form = new VersionEditForm(cboModule.Items, cboModule.SelectedIndex, mVersionTable, selectedRows[0].Index);
                form.Text = "编辑版本";
                if (form.ShowDialog() == DialogResult.OK)
                {
                    LoadModule();
                    LoadVersionData();
                }    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnDeleteVersion_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewSelectedRowCollection selectedRows = dgvVersion.SelectedRows;
                if (selectedRows.Count == 0)
                    return;
                if (MessageBox.Show("版本一旦删除将不可恢复，确定要继续吗？", "警告",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
                    return;
                DBHelper.BeginCommand();
                DBHelper.ExecuteCommand("DELETE FROM " + SysUpdateFile.TableName
                    + " WHERE " + SysUpdateVersion.Id + "=" + mVersionTable.Rows[selectedRows[0].Index][SysUpdateVersion.Id].ToString());
                DBHelper.ExecuteCommand("DELETE FROM " + SysUpdateVersion.TableName
                    + " WHERE " + SysUpdateVersion.Id + "=" + mVersionTable.Rows[selectedRows[0].Index][SysUpdateVersion.Id].ToString());
                DBHelper.EndCommand();
                LoadModule();
                LoadVersionData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void CreateUpdateFiles(bool locked)
        {
            if (string.IsNullOrEmpty(cboModule.Text))
            {
                MessageBox.Show("未选择任何模块！",
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }

            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                this.Cursor = Cursors.WaitCursor;

                string basePath = Path.Combine(Application.StartupPath, "UpdateFiles");
                List<string> localFiles = Autoupdate.Common.Common.GetLocalFiles(basePath, false);
                foreach (string file in localFiles)
                {
                    string destFile = Path.Combine(folderBrowserDialog.SelectedPath, Util.GetRelativePath(basePath, file));
                    string path = Path.GetDirectoryName(destFile);
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    File.Copy(file, destFile, true);
                }

                string configFile = folderBrowserDialog.SelectedPath + "\\Update\\File.cfg";
                Configuration config = new Configuration(null);
                config.WriteString(SysUpdateVersion.Module, cboModule.Text, true);
                config.WriteString(SysUpdateVersion.Locked, locked ? "1" : "0", true);
                config.Save(configFile);

                basePath = Path.Combine(Application.StartupPath, "Data");
                localFiles = Autoupdate.Common.Common.GetLocalFiles(basePath, false);
                foreach (string file in localFiles)
                {
                    string destFile = Path.Combine(folderBrowserDialog.SelectedPath, Path.Combine("Update", Util.GetRelativePath(basePath, file)));
                    string path = Path.GetDirectoryName(destFile);
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    File.Copy(file, destFile, true);
                }

                MessageBox.Show("文件更新包创建成功！",
                    "提示",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                this.Cursor = Cursors.Default;
            }
        }

        private void LoadVersionData()
        {
            mVersionTable.Rows.Clear();
            mVersionTable.Columns.Clear();
            dgvVersion.DataSource = null;

            btnCreateTestUpdateFiles.Enabled = false;
            btnbtnCreateUpdateFiles.Enabled = false;

            int index = cboModule.SelectedIndex;
            if (index == -1)
                return;

            if (!string.IsNullOrEmpty(cboModule.Text))
            {
                btnCreateTestUpdateFiles.Enabled = true;
                btnbtnCreateUpdateFiles.Enabled = true;
            }

            mConfig.WriteString(ModuleName, cboModule.Items[index].ToString(), true);

            DBHelper.FillTable("SELECT * FROM " + SysUpdateVersion.TableName
                + " WHERE " + SysUpdateVersion.Module + "='" + cboModule.Items[index].ToString() + "'"
                + " ORDER BY " + SysUpdateVersion.Id, mVersionTable);
            dgvVersion.DataSource = mVersionTable;
            foreach (DataGridViewColumn column in dgvVersion.Columns)
            {
                if (column.Name == SysUpdateVersion.Name
                    || column.Name == SysUpdateVersion.Time
                    || column.Name == SysUpdateVersion.Locked)
                    column.Visible = true;
                else
                    column.Visible = false;
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            dgvVersion.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvVersion.Columns[SysUpdateVersion.Time].Width = 80;
            dgvVersion.Columns[SysUpdateVersion.Locked].Width = 50;
        }

        private void LoadFile()
        {
            lblFileCount.Text = string.Empty;
            txtDescription.Text = string.Empty;
            mFileTable.Columns.Clear();
            mFileTable.Rows.Clear();
            dgvFileList.Columns.Clear();
            dgvFileList.DataSource = null;

            btnModifyVersion.Enabled = false;
            btnDeleteVersion.Enabled = false;

            DataGridViewSelectedRowCollection selectedRows = dgvVersion.SelectedRows;
            if (selectedRows.Count == 0)
                return;

            if (selectedRows[0].Index == mVersionTable.Rows.Count - 1)
            {
                btnModifyVersion.Enabled = true;
                btnDeleteVersion.Enabled = true;
            }

            txtDescription.Text = mVersionTable.Rows[selectedRows[0].Index][SysUpdateVersion.Description].ToString();
            DBHelper.FillTable("SELECT * FROM " + SysUpdateFile.TableName
                + " WHERE " + SysUpdateVersion.Id + "='" + mVersionTable.Rows[selectedRows[0].Index][SysUpdateVersion.Id].ToString() + "'",
                mFileTable);
            mFileTable.Columns.Add(SysUpdateFile.Status);

            lblFileCount.Text = "(" + mFileTable.Rows.Count + ")";
            UpdateFileView(dgvFileList, mFileTable, false, false);
        }

        private void dgvFileList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            e.Graphics.DrawString((e.RowIndex + 1).ToString(),
                this.Font,
                SystemBrushes.ControlText,
                new Rectangle(e.RowBounds.Left, e.RowBounds.Top, dgv.RowHeadersWidth, e.RowBounds.Height),
                new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
        }

        public static void UpdateFileView(DataGridView dgvFile, DataTable fileTable, bool editUsage,  bool showStatus)
        {
            dgvFile.Columns.Clear();
            dgvFile.DataSource = null;

            foreach (DataColumn column in fileTable.Columns)
            {
                if (column.ColumnName == SysUpdateFile.Usage)
                {
                    DataGridViewComboBoxColumn newColumn = new DataGridViewComboBoxColumn()
                    {
                        Name = column.ColumnName,
                        DataPropertyName = column.ColumnName,
                        DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
                    };
                    newColumn.Items.AddRange(new object[] { "", FileUsage.Run, FileUsage.Icon, FileUsage.PreUpdate, FileUsage.PostUpdate, FileUsage.Ignore });
                    dgvFile.Columns.Add(newColumn);
                }
                else
                    dgvFile.Columns.Add(new DataGridViewTextBoxColumn() { Name = column.ColumnName, DataPropertyName = column.ColumnName });
            }
            dgvFile.AutoGenerateColumns = false;
            dgvFile.DataSource = fileTable;
            foreach (DataGridViewColumn column in dgvFile.Columns)
            {
                if (column.Name == SysUpdateFile.Index
                    || column.Name == SysUpdateVersion.Id
                    || column.Name == SysUpdateFile.Data)
                    column.Visible = false;
                else
                    column.Visible = true;
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
                if (column.Name == SysUpdateFile.Usage && editUsage)
                    column.ReadOnly = false;
                else
                    column.ReadOnly = true;
            }
            dgvFile.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvFile.Columns[SysUpdateFile.Name].Width = 200;

            dgvFile.Columns[SysUpdateFile.Name].HeaderText = "文件名";
            dgvFile.Columns[SysUpdateFile.Path].HeaderText = "路径";
            dgvFile.Columns[SysUpdateFile.MD5].HeaderText = "MD5值";
            dgvFile.Columns[SysUpdateFile.Usage].HeaderText = "用途";
            dgvFile.Columns[SysUpdateFile.Status].HeaderText = "处理";

            dgvFile.Columns[SysUpdateFile.Status].Visible = showStatus;
        }

        private void contextMenuStrip1_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                tsmLockUpdate.Visible = false;
                tsmUnlockUpdate.Visible = false;

                DataGridViewSelectedRowCollection selectedRows = dgvVersion.SelectedRows;
                if (selectedRows.Count == 0)
                {
                    e.Cancel = true;
                    return;
                }
                if (selectedRows[0].Index != mVersionTable.Rows.Count - 1)
                {
                    e.Cancel = true;
                    return;
                }
                string locked = mVersionTable.Rows[selectedRows[0].Index][SysUpdateVersion.Locked].ToString();
                if (locked == "0" || locked.ToUpper() == "FALSE")
                    tsmLockUpdate.Visible = true;
                else
                    tsmUnlockUpdate.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void tsmUnlockUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewSelectedRowCollection selectedRows = dgvVersion.SelectedRows;
                if (selectedRows.Count == 0)
                    return;
                DBHelper.ExecuteCommand("UPDATE " + SysUpdateVersion.TableName
                    + " SET " + SysUpdateVersion.Locked + "=0"
                    + " WHERE " + SysUpdateVersion.Id + "=" + mVersionTable.Rows[selectedRows[0].Index][SysUpdateVersion.Id].ToString());
                LoadVersionData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void tsmLockUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewSelectedRowCollection selectedRows = dgvVersion.SelectedRows;
                if (selectedRows.Count == 0)
                    return;
                DBHelper.ExecuteCommand("UPDATE " + SysUpdateVersion.TableName
                    + " SET " + SysUpdateVersion.Locked + "=1"
                    + " WHERE " + SysUpdateVersion.Id + "=" + mVersionTable.Rows[selectedRows[0].Index][SysUpdateVersion.Id].ToString());
                LoadVersionData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            try
            {
                using (FolderBrowserDialog fbd = new FolderBrowserDialog())
                {
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        foreach (DataRow dr in mFileTable.Rows)
                        {
                            string file = Path.Combine(fbd.SelectedPath, dr[SysUpdateFile.Path].ToString());
                            string path = Path.GetDirectoryName(file);
                            if (!Directory.Exists(path))
                                Directory.CreateDirectory(path);
                            Util.StreamToFile(Util.BytesToStream((byte[])dr[SysUpdateFile.Data]), file);
                        }
                        MessageBox.Show("版本下载完成！",
                            "提示",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace,
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Text += "," + AssemblyVersion;
        }
    }
}
